package com.typy.www.tpay;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.typy.www.tpay.base.BaseActivity;
import com.typy.www.tpay.bean.bean.BaseReturn;
import com.typy.www.tpay.bean.vm.LoginVm;
import com.typy.www.tpay.constance.Constance;
import com.typy.www.tpay.constance.Sharep;
import com.typy.www.tpay.ui.acitivity.ForgetPassWordActivity;
import com.typy.www.tpay.ui.acitivity.HomeActivity;
import com.typy.www.tpay.ui.acitivity.RegisterActivity;
import com.typy.www.tpay.util.CheckUtil;
import com.typy.www.tpay.util.GsonUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.MessageAction;
import com.typy.www.tpay.constance.MessageEvent;
import com.typy.www.tpay.util.ParamsUtil;
import com.typy.www.tpay.util.PreferencesUtil;
import com.typy.www.tpay.util.SharedPreferencesUtil;
import com.typy.www.tpay.util.StringUtil;
import com.typy.www.tpay.util.ToastUtil;
import com.typy.www.tpay.util.UiHelper;
import com.typy.www.tpay.volley.HTTPUtils;
import com.typy.www.tpay.volley.VolleyListener;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 13799 on 2018/5/29.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.tv_userName)
    EditText tvUserName;
    @BindView(R.id.tv_password)
    EditText tvPassword;
    @BindView(R.id.forgetPassword)
    TextView forgetPassword;
    @BindView(R.id.btn_login)
    TextView btnLogin;
    @BindView(R.id.btn_regist)
    Button btnRegist;
    String addressTemp;
    String addressPer;
    private long exitTime = 0;

    public static void show(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }


    @Override
    protected int getContentResId() {
        return R.layout.activity_login;
    }

    @Override
    protected int getTitleBarResId() {
        return -1;
    }

    @Override
    public int getStatusBarColor() {
        return R.color.statusbar_blue3D5BC9;
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //自动登录
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        setLoginName();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBus(MessageEvent msg){
        if(msg.getKey().equals(MessageAction.REFRESHLOGINNAME)){
            setLoginName();
        }
    }
    private void setLoginName(){
        if (!StringUtil.isEmpty(PreferencesUtil.getValue(Sharep.FDCODE)) && tvUserName != null) {
            tvUserName.setText(PreferencesUtil.getValue(Sharep.FDCODE));
            tvPassword.setFocusable(true);
            tvPassword.setFocusableInTouchMode(true);
            tvPassword.requestFocus();
        }
    }


    @OnClick({R.id.forgetPassword, R.id.btn_login, R.id.btn_regist})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forgetPassword:
                ForgetPassWordActivity.show(this,Constance.REFINDPASSWORD);
                break;
            case R.id.btn_login:
                check();
                break;
            case R.id.btn_regist:
                if (CheckUtil.checkText(getActivity(),tvUserName)&&CheckUtil.checkPhoneTrue(getActivity(),tvUserName)){
                dogetsmscode(tvUserName.getText().toString(),"0");
        }
//                RegisterActivity.show(this);
                break;
        }
    }

    private void check() {
        if (CheckUtil.checkText(getActivity(),tvUserName)&&CheckUtil.checkPhoneTrue(getActivity(),tvUserName)&&CheckUtil.checkText(getActivity(),tvPassword)) {
            doLogin(tvUserName.getText().toString(), tvPassword.getText().toString());
        }
    }


    public void dogetsmscode(final String username, final String smsmode) {

        Logutil.print("执行请求");
        ParamsUtil params=new ParamsUtil();
        params.put("mobile", username);
        params.putMd5("smsmode",smsmode);
//        HTTPUtils.post( getActivity(),Constance.getLoginURL(), params.getParams(), new VolleyListener() {
//            @Override
//            public void onResponse(BaseReturn ret) {
//                UiHelper.showToast(getActivity(),"登录成功");
//
//                LoginVm vm= GsonUtils.parseJSON(ret.getData().toString(),LoginVm.class);
//                if(vm!=null){
//                    PreferencesUtil.save(Sharep.FDCODE,vm.getFdCode());
//                    PreferencesUtil.save(Sharep.TOKEN,vm.getToken());
//                    PreferencesUtil.save(Sharep.REFRESHTOKEN,vm.getRefreshToken());
//                    PreferencesUtil.save(Sharep.PASSWORD,StringUtil.MD5(password));
//        HomeActivity.show(getActivity());
//                    finish();
//                }
//            }
//            @Override
//            public void onResponseErr(int code, String msg) {
//                UiHelper.showToast(getActivity(),msg);
//            }
//        });
//        HTTPUtils.get(getActivity(), "http://www.zhaodui.com.cn/jeecg-boot/sys/getCheckCode", new VolleyListener() {
//            @Override
//            public void onResponse(BaseReturn ret) {
//                Logutil.print("接收数据   "+ret.toString());
//
//            }
//
//            @Override
//            public void onResponseErr(int code, String msg) {
//
//                Logutil.print("接收数据2");
//            }
//        });

        HTTPUtils.post( getActivity(),Constance.getGetcodeURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {

                LoginVm vm= GsonUtils.parseJSON(ret.getData().toString(),LoginVm.class);
                if(vm!=null){
//                    PreferencesUtil.save(Sharep.FDCODE,vm.getFdCode());
//                    PreferencesUtil.save(Sharep.TOKEN,vm.getToken());
//                    PreferencesUtil.save(Sharep.REFRESHTOKEN,vm.getRefreshToken());
//                    PreferencesUtil.save(Sharep.PASSWORD,StringUtil.MD5(password));
                    UiHelper.showToast(getActivity(),"验证码发送成功");

                    finish();
                }
            }
            @Override
            public void onResponseErr(int code, String msg) {
                UiHelper.showToast(getActivity(),msg);
            }
        });
    }


    public void doLogin(final String username, final String password) {

        Logutil.print("执行请求");
        ParamsUtil params=new ParamsUtil();
        params.put("mobile", username);
        params.putMd5("captcha",password);
//        HTTPUtils.post( getActivity(),Constance.getLoginURL(), params.getParams(), new VolleyListener() {
//            @Override
//            public void onResponse(BaseReturn ret) {
//                UiHelper.showToast(getActivity(),"登录成功");
//
//                LoginVm vm= GsonUtils.parseJSON(ret.getData().toString(),LoginVm.class);
//                if(vm!=null){
//                    PreferencesUtil.save(Sharep.FDCODE,vm.getFdCode());
//                    PreferencesUtil.save(Sharep.TOKEN,vm.getToken());
//                    PreferencesUtil.save(Sharep.REFRESHTOKEN,vm.getRefreshToken());
//                    PreferencesUtil.save(Sharep.PASSWORD,StringUtil.MD5(password));
//                    HomeActivity.show(getActivity());
//                    finish();
//                }
//            }
//            @Override
//            public void onResponseErr(int code, String msg) {
//                UiHelper.showToast(getActivity(),msg);
//            }
//        });
//        HTTPUtils.get(getActivity(), "http://www.zhaodui.com.cn/jeecg-boot/sys/getCheckCode", new VolleyListener() {
//            @Override
//            public void onResponse(BaseReturn ret) {
//                Logutil.print("接收数据   "+ret.toString());
//
//            }
//
//            @Override
//            public void onResponseErr(int code, String msg) {
//
//                Logutil.print("接收数据2");
//            }
//        });

        HTTPUtils.post( getActivity(),Constance.getLoginURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                UiHelper.showToast(getActivity(),"登录成功");

                LoginVm vm= GsonUtils.parseJSON(ret.getData().toString(),LoginVm.class);
                if(vm!=null){
//                    PreferencesUtil.save(Sharep.FDCODE,vm.getFdCode());
//                    PreferencesUtil.save(Sharep.TOKEN,vm.getToken());
//                    PreferencesUtil.save(Sharep.REFRESHTOKEN,vm.getRefreshToken());
//                    PreferencesUtil.save(Sharep.PASSWORD,StringUtil.MD5(password));
                    HomeActivity.show(getActivity());
                    finish();
                }
            }
            @Override
            public void onResponseErr(int code, String msg) {
                UiHelper.showToast(getActivity(),msg);
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.show(this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                if(HomeActivity.instance!=null){
                    HomeActivity.instance.finish();
                }
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
